package com.difsonapps.android.marker.dialogs;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.ImageLoader;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.IRefresher;
import com.difsonapps.android.marker.MainActivity;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class SharePhotoOnMarkItDialog extends Dialog{
	IRefresher<Photo> executer;
	Photo photo;
	//MainActivity activity;
	
	EditText name;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    ProgressDialog loadingProgressDialog;
	
	public SharePhotoOnMarkItDialog(Context context, Photo photo, IRefresher<Photo> executer) {
		super(context);
		//super(context, R.style.mydialogstyle);
		if(photo==null){
			executer.refresh(null);
			cancelAction();
		}
		this.photo = photo;
		this.executer = executer;
		setTitle(R.string.share_on_mark_it);
		setContentView(R.layout.dialog_share_photo_on_mark_it);
		
		com.android.volley.toolbox.NetworkImageView imageView = (com.android.volley.toolbox.NetworkImageView)findViewById(R.id.imageThumb);
		if(photo.getImage()!=null) imageView.setImageUrl(MarkerUtil.buildImageUrl(photo.getImage(), AppConstant.IMAGES_FOLDER, null), imageLoader);
		name = (EditText)findViewById(R.id.name);
		
		findViewById(R.id.share_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				shareOnMarkIt();
			}
		});
		findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelAction();
			}
		});
	}
	
	private void shareOnMarkIt(){		
		Log.d("Share Photo", "Confirm sharing photo");
		sharePhoto(photo);
	}
	
	private void sharePhoto(Photo photo){
    	Map<String, String> params = new HashMap<String, String>();
        params.put("id", ""+photo.getId());
        params.put("name", name.getText().toString());
        
		showProgress();
		String url = AppConstant.sharePhotoUrl;
		
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				url, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	//Log.i("Response", response.toString());
                    	parseJsonSharePhoto(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	//Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
    }
    
	
	private void parseJsonSharePhoto(JSONObject response){
		try {
			if(response.has("result_code")){
				String resultCode = response.getString("result_code");
				if(resultCode.equals("success") || resultCode.equals("ok")){
					//toast("Photo liked");
					Photo photo = response.has("photo")?Photo.parseFromJsonObject(response.getJSONObject("photo")):null;
					hideProgress();
					if(photo!=null) {
						toast("Photo shared");
						executer.refresh(photo);
						dismiss();
					}
	            	return;
				}
			}
        } catch (JSONException e) {
            e.printStackTrace();
        }
		toast(getContext().getResources().getString(R.string.an_error_occured));
        hideProgress();
	}
	
	private void cancelAction(){
		dismiss();
	}
	boolean show_progress = true;
    private void showProgress(){
    	if(!show_progress) return;
		loadingProgressDialog = ProgressDialog.show(getContext(), getContext().getResources().getString(R.string.loading), getContext().getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
	}
	
	private void hideProgress(){
    	if(!show_progress) return;
		if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
	}
	public void toast(String text){
		Toast.makeText(this.getContext(), text, Toast.LENGTH_SHORT).show();
	}

}
